/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLER;

import COMMON.NganHangCauHoi;
import MODEL.DAO.CustomizeQuizsDao;
import MODEL.DAO.TestResultsDao;
import MODEL.DAO.WarehousesDao;
import MODEL.POJO.Customizequizs;
import MODEL.POJO.Testresults;
import MODEL.POJO.Users;
import MODEL.POJO.Warehouses;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Quangbt
 */
@WebServlet(name = "ResultController", urlPatterns = {"/ResultController"})
public class ResultController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        try {
            String action = (String) request.getParameter("action");
            if (action != null) {
                if (action.equals("result")) {
                    session.setAttribute("checked", null);
                    session.removeAttribute("checked");
                    Users u = (Users) session.getAttribute("user");
                    String examCode = (String) request.getParameter("examCode");
                    String orderQuestion = (String) request.getParameter("orderQuestion");
                    Warehouses wh = WarehousesDao.LayDeThiTheoMa(Integer.parseInt(examCode));
                    int sum = wh.getCustomizequizs().getCustomizeQuizQualityEasy() + wh.getCustomizequizs().getCustomizeQuizQualityMedium() + wh.getCustomizequizs().getCustomizeQuizQualityHard();
                    String answer = ""; // Câu trả lời của người dùng
                    for (Integer i = 1; i <= sum; i++) {
                        String value = (String) request.getParameter(i.toString());
                        if (value == null) {
                            value = "0";
                        }
                        answer = answer + value;
                        if (i != sum) {
                            answer = answer + ",";
                        }
                    }

                    //String mergeQuestion = wh.getWarehouseEasy() + wh.getWarehouseMedium() + wh.getWarehouseHard();
                    Hashtable htAnswer = NganHangCauHoi.getAnswer(orderQuestion);
                    int result = NganHangCauHoi.countAnswerRight(htAnswer, orderQuestion, answer);
                    float score = (float) result / sum * 10;
                    score = (float) Math.ceil(score * 2) / 2;
                    Testresults tr = TestResultsDao.getResultFromExamCode(Integer.parseInt(examCode), u.getUserId());
                    tr.setTestResultDateTimeEnded(new java.sql.Date(new java.util.Date().getTime()));
                    tr.setTestResultScore(score);
                    tr.setTestResultAnswers(answer);
                    boolean kq = TestResultsDao.updateResult(tr);

                    ArrayList dsch = new ArrayList();
                    dsch = NganHangCauHoi.getQuestionFromWarehouse(orderQuestion);
                    request.setAttribute("examCode", examCode);
                    request.setAttribute("dsch", dsch);
                    request.setAttribute("answer", answer);
                    request.setAttribute("result", result);
                    request.setAttribute("score", score);
                    request.setAttribute("testing", "0");
                    request.getRequestDispatcher("User/Result.jsp").forward(request, response);
                }
                else if (action.equals("viewdetails")) {
                    Users u = (Users) session.getAttribute("user");
                    String examCode = (String) request.getParameter("examcode");

                    Testresults tr = TestResultsDao.getResultFromExamCode(Integer.parseInt(examCode), u.getUserId());
                    String orderQuestion = tr.getTestResultNumberOrder();
                    int sum = tr.getWarehouses().getCustomizequizs().getCustomizeQuizQualityEasy() + tr.getWarehouses().getCustomizequizs().getCustomizeQuizQualityMedium() + tr.getWarehouses().getCustomizequizs().getCustomizeQuizQualityHard();
                    String answer = tr.getTestResultAnswers(); // Câu trả lời của người dùng
                   
                    //String mergeQuestion = wh.getWarehouseEasy() + wh.getWarehouseMedium() + wh.getWarehouseHard();
                    Hashtable htAnswer = NganHangCauHoi.getAnswer(orderQuestion);
                    int result = NganHangCauHoi.countAnswerRight(htAnswer, orderQuestion, answer);
                    float score = (float) result / sum * 10;
                    score = (float) Math.ceil(score * 2) / 2;

                    ArrayList dsch = new ArrayList();
                    dsch = NganHangCauHoi.getQuestionFromWarehouse(orderQuestion);
                    request.setAttribute("examCode", examCode);
                    request.setAttribute("dsch", dsch);
                    request.setAttribute("answer", answer);
                    request.setAttribute("result", result);
                    request.setAttribute("score", score);
                    request.setAttribute("testing", "0");
                    request.getRequestDispatcher("User/Result.jsp").forward(request, response);
                }
                else
                {
                    request.getRequestDispatcher("User/Result.jsp").forward(request, response);
                }
            }

        } finally {
            //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
